var express = require('express')
var router = express.Router()

const { getALL, getById, exec } = require('../db')

//获取所有类型:GET/categories
router.get('/', async (req, res) => {
  //解析请求参数
  const { page = 1, size = 5 } = req.query
  //偏移量 offset = (page - 1)*size
  let offset = (page - 1) * size
  let sql = `select count(*) as total from categories`
  const { total } = await getById(sql)
  //操作数据库
  sql = `select id,category_name from categories order by id desc limit ${offset},${size}`
  const data = await getALL(sql)
  res.send({
    code: 0,
    message: '获取分类成功',
    result: {
      total,
      data,
    },
  })
})

//获取单个用户:GET/categories/id
router.get('/:id', async (req, res) => {
  //1.解析请求参数
  const { id } = req.params
  //2.操作数据库
  let sql = `select * from categories where id =${id}`
  const data = await getById(sql)
  //3.返回结果
  res.send({
    code: 0,
    message: '获取单个分类成功',
    result: data,
  })
})

//添加分类:POST/categories/id
router.post('/', async (req, res) => {
  //解析参数
  const { category_name } = req.body
  //操作数据库
  let sql = `insert into categories(category_name) values('${category_name}')`
  const data = await exec(sql)
  res.send({
    code: 0,
    message: '添加分类成功',
    result: {
      id: data.insertId,
      category_name,
    },
  })
})
module.exports = router
